﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractMes;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.PalletInfos;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Devices;
using HamcoWcs.Models.TibcoMessage;
using System.Linq;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    /// <summary>
    /// 托盘取出WCS系统
    /// </summary>
    public class PconMsgParse_PickDown : PconMsgParseBase
    {
        private readonly ILoggerService _logger;
        public override EnumPconPlcRequest RequestType => EnumPconPlcRequest.PickDown;


        public PconMsgParse_PickDown(WcsDbContext wcsDbContext, IMapper mapper, IMesCommunicateService mesCommunicateService, ILoggerService logger)
            : base(mesCommunicateService, wcsDbContext, mapper)
        {
            _logger = logger;
        }

        public override void Deal(PconDto pconDto, PconPlc pconPlc)
        {
            //_logger.AddWcsRunLog(pconDto.UnitId, $"{pconDto.DeviceName}托盘搬下");

            if (!string.IsNullOrEmpty(pconDto.UnitId))
            {
                try
                {
                    var pallet = _wcsDbContext.Set<PalletInfo>().FirstOrDefault(x => x.UnitId == pconDto.UnitId);
                    if (pallet != null)
                    {
                        pallet.OrderNumber = "";
                        pallet.PalletStatus = "OUT";
                        pallet.PalletType = "";
                        _wcsDbContext.SaveChanges();
                    }
                }
                catch (System.Exception ex)
                {
                    _logger.AddSystemErrorLog($"PconMsgParse->PickDown:取出操作时发生异常,{ex.Message}");
                }
            }

            if (string.IsNullOrEmpty(pconDto.UnitId))
            {
                _logger.AddWcsRunLog(pconDto.UnitId, $"{pconDto.DeviceName}上报托盘取下时未携带托盘号，PconMode:{pconDto.PconMode},WorkType:{pconDto.WorkType}");
            }
            else
            {
                // 上报托盘out PalletLocationChangedReport
                _mesCommunicateService.PalletLocationChangedReport(new PalletLocationChangedReportMessage(new PalletLocationChangedReportMessageBody()
                {
                    ActionType = "OUT",
                    CurrentMachineName = pconDto.MachineName,
                    CurrentPositionName = pconDto.PortName,
                    CurrentPositionType = "PORT",
                    CurrentZoneName = "",
                    EventUser = pconDto.MachineName,
                    PalletName = pconDto.UnitId,
                }));
                _logger.AddWcsRunLog(pconDto.UnitId, $"{pconDto.DeviceName}上报托盘取下，PconMode:{pconDto.PconMode},WorkType:{pconDto.WorkType}");
            }
        }
    }
}
